package com.situ.meetingRoom.controller;


import com.situ.meetingRoom.entity.Result;
import com.situ.meetingRoom.entity.User;
import com.situ.meetingRoom.service.UserService;
import com.situ.meetingRoom.service.impl.UserServiceImpl;
import com.situ.meetingRoom.util.BaseServlet;
import com.situ.meetingRoom.util.PageInfo;
import com.situ.meetingRoom.vo.UserVO;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;


@WebServlet(name = "UserServlet", value = "/user")
public class UserServlet extends BaseServlet {
    private UserService userService = new UserServiceImpl();

    public void logout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.getWriter().append("logout");
        //从session中清除登录状态
        request.getSession().invalidate();
        //请求转发还是重定向
        response.sendRedirect("user/login.jsp");
    }

    public void login(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String sId = request.getParameter("id");
        String password = request.getParameter("password");
        String verCode = request.getParameter("verCode");
        String sRemember = request.getParameter("remember");
        Boolean remember = false;
        try {
            remember = Boolean.parseBoolean(sRemember);
        } catch (Exception e) {}

        Integer id = null;
        try {
            try {
                id = Integer.parseInt(sId);
            } catch (NumberFormatException e) {
                throw new Exception("工号不合法");
            }

//            2.验证参数
            if (password == null || password.length() < 3 || password.length() > 16) {
                throw new Exception("密码不对");
            }
            //验证验证码 verCode 生成在session
            String sVerCode = (String) request.getSession().getAttribute("verCode");
            if (sVerCode == null || !sVerCode.equalsIgnoreCase(verCode)) {
                throw new Exception("验证码错误");
            }

            User user = new User();
            user.setId(id);
            user.setPassword(password);
//            调用service
            user = userService.login(user);
            if (remember){
                //需要客户端保存账号使用Cookie
                Cookie idCookie = new Cookie("sId",sId);
                Cookie passwordCookie = new Cookie("password",password);
                response.addCookie(idCookie);
                response.addCookie(passwordCookie);

                Cookie rememberCookie = new Cookie("remember",remember+"");
                response.addCookie(rememberCookie);
            }

//            保存到session
            request.getSession().setAttribute("user", user);
//            跳转主页面
            response.sendRedirect("index.jsp");
        } catch (Exception e) {
//            登录失败
            request.setAttribute("error", e.getMessage());
//            返回登陆界面
            request.getRequestDispatcher("user/login.jsp").forward(request, response);
        }
    }

    public void resetPwd(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1-获取参数
        String oldPwd = request.getParameter("oldPwd");
        String newPwd = request.getParameter("newPwd");
        String rePwd = request.getParameter("rePwd");
        try {
            //2-校验参数 //3-16
            if (oldPwd == null || !oldPwd.matches("^.{3,16}$")) {
                throw new Exception("旧密码格式不正确");
            }
            if (newPwd == null || !newPwd.matches("^.{3,16}$")) {
                throw new Exception("新密码格式不正确");
            }
            if (rePwd == null || !rePwd.equals(newPwd)) {
                throw new Exception("两次密码不一致");
            }

//            获取当前登录的员工,如果员工没登录
            User user = (User) request.getSession().getAttribute("user");
//            3-调用service
            userService.resetPwd(oldPwd, newPwd, user.getId());
            //修改成功
            request.getSession().invalidate();
            //返回JSON
            response.setContentType("application/json; charset=UTF-8");
            response.getWriter().append("{\"code\": 0}");

        } catch (Exception e) {
            e.printStackTrace();
            //修改失败
            //返回JSON    失败， 错误信息
            response.setContentType("application/json; charset=UTF-8");
            response.getWriter().append("{\"code\": 1, \"msg\": \"" + e.getMessage() + "\"}");
        }
    }

    public void modify(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //1-获取参数
        String tel = request.getParameter("tel");
        String email = request.getParameter("email");
        String head = request.getParameter("head");
        try {
            //2-参数校验
            if (tel == null || !tel.matches("^1[35-9][0-9]{9}$")) {
                throw new Exception("电话格式错误");
            }
            if (email == null || !email.matches("^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$")) {
                throw new Exception("邮箱格式错误");
            }

            //3-调用Service
            User luser = (User) request.getSession().getAttribute("user");

            User user = new User();
            user.setTel(tel);
            user.setEmail(email);
            user.setHead(head);
            user.setId(luser.getId());
            userService.edit(user);

            //修改成功  更新一下当前登录员工信息
            luser = userService.getById(luser.getId());
            request.getSession().setAttribute("user", luser);

            response.setContentType("application/json; charset=UTF-8");
            response.getWriter().append("{\"code\": 0}");
        } catch (Exception e) {
            e.printStackTrace();
            response.setContentType("application/json; charset=UTF-8");
            response.getWriter().append("{\"code\": 1, \"msg\": \"" + e.getMessage() + "\"}");
        }
    }

    public void search(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //分页
        //获取参数
        String sPage = request.getParameter("page");
        String sLimit = request.getParameter("limit");
        //1-获取参数
        String name = request.getParameter("name");
        String sex = request.getParameter("sex");
        String sRole = request.getParameter("role");
        String sStatus = request.getParameter("status");
        String sDeptId = request.getParameter("deptId");

        User user = new User();
        user.setName(name);
        user.setSex(sex);
        if (sRole != null && sRole.length() > 0) {
            user.setRole(Integer.parseInt(sRole));
        }
        if (sStatus != null && sStatus.length() > 0) {
            user.setStatus(Integer.parseInt(sStatus));
        }
        if (sDeptId != null && sDeptId.length() > 0) {
            user.setDeptId(Integer.parseInt(sDeptId));
        }

        Integer page = null, limit = null;
        try {
            page = Integer.parseInt(sPage);
            limit = Integer.parseInt(sLimit);
        } catch (Exception e) {
        }
        //判断是否分页
        if (page != null) {
            //分页
            PageInfo pageInfo = userService.getForPage(page, limit, user);
            response.setContentType("application/json; charset=UTf-8");
            response.getWriter().append(Result.ok(pageInfo).toJson());
        } else {
            List<UserVO> users = userService.getAll(user);

            //返回，以JSON格式返回
            response.setContentType("application/json; charset=UTf-8");
            response.getWriter().append(Result.ok(users).toJson());
        }
    }

    public void remove(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1-获取参数
        String sId = request.getParameter("id");
        try {
            Integer id = Integer.parseInt(sId);

            //2-调用service
            userService.remove(id);

            //3-返回数据
            response.setContentType("application/json; charset=UTF-8");
            response.getWriter().append(Result.ok().toJson());
        } catch (Exception e) {
            e.printStackTrace();
            response.setContentType("application/json; charset=UTF-8");
            response.getWriter().append(Result.error(e.getMessage()).toJson());
        }
    }

    public void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1-获取参数
        String name = request.getParameter("name");
        String sex = request.getParameter("sex");
        String tel = request.getParameter("tel");
        String email = request.getParameter("email");
        String sRole = request.getParameter("role");
        String sDeptId = request.getParameter("deptId");

        Integer role = Integer.parseInt(sRole);
        Integer DeptId = Integer.parseInt(sDeptId);

        //2-参数校验

        //3-调用service
        User user = new User();
        user.setName(name);
        user.setSex(sex);
        user.setTel(tel);
        user.setEmail(email);
        user.setRole(role);
        user.setDeptId(DeptId);

        user.setPassword("123");//给定一个默认密码
        try {
            userService.add(user);
            response.setContentType("application/json; charset=UTF-8");
            response.getWriter().append(Result.ok().toJson());
        } catch (Exception e) {
            e.printStackTrace();
            response.setContentType("application/json; charset=UTF-8");
            response.getWriter().append(Result.error(e.getMessage()).toJson());
        }
    }

    public void getById(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1-获取参数
        String sId = request.getParameter("id");

        Integer id = Integer.parseInt(sId);

        //2-调用service
        User user = userService.getById(id);

        response.setContentType("application/json; charset=UTF-8");
        response.getWriter().append(Result.ok(user).toJson());


    }

    public void edit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1-获取参数
        String sId = request.getParameter("id");
        String name = request.getParameter("name");
        String sex = request.getParameter("sex");
        String tel = request.getParameter("tel");
        String email = request.getParameter("email");
        String sRole = request.getParameter("role");
        String sDeptId = request.getParameter("deptId");

        Integer id = Integer.parseInt(sId);
        Integer role = Integer.parseInt(sRole);
        Integer DeptId = Integer.parseInt(sDeptId);

        //2-参数校验

        //3-调用service
        User user = new User();
        user.setId(id);
        user.setName(name);
        user.setSex(sex);
        user.setTel(tel);
        user.setEmail(email);
        user.setRole(role);
        user.setDeptId(DeptId);

        try {
            userService.edit(user);
            response.setContentType("application/json; charset=UTF-8");
            response.getWriter().append(Result.ok().toJson());
        } catch (Exception e) {
            e.printStackTrace();
            response.setContentType("application/json; charset=UTF-8");
            response.getWriter().append(Result.error(e.getMessage()).toJson());
        }
    }
}

